package yb.ecp.fast.infra.security;

import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import yb.ecp.fast.infra.infra.CommonUtil;

import java.util.List;

@Slf4j
@Service
@RefreshScope
public class LogoutFilter implements GlobalFilter, Ordered {
    @Value("${fast.auth.logout.url}")
    private List<String> logoutUrls;

    @Value("${fast.auth.logout.redirectUrl:/login}")
    private String logoutRedirectUrl;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = exchange.getRequest().getURI().getPath();
        if (shouldFilter(path)) {
            String token = exchange.getRequest().getHeaders().getFirst(CommonUtil.DEFAULT_TOKEN_KEY);
            if (StringUtils.isBlank(token)) {
                token = exchange.getRequest().getQueryParams().getFirst(CommonUtil.DEFAULT_TOKEN_KEY);
            }
            if (!StringUtils.isBlank(token)) {
                redisTemplate.delete(CommonUtil.genTokenKey(token));
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, logoutRedirectUrl);
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                return response.setComplete();
            }
        }
        return chain.filter(exchange.mutate().request(request).build());
    }

    private boolean shouldFilter(String requestUri) {
        for (String url : logoutUrls) {
            if (requestUri.matches(url)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
